package ru.adhoc.truealarm.barcodreader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import ru.adhoc.truealarm.R;
import ru.adhoc.truealarm.utils.Util;

import android.content.pm.ActivityInfo;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.Button;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Size;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;

/**
 * Created by Малюгин Сергей on 24.09.13.
 */
public class CameraTestActivity extends Activity {

    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;
    TextView scanText;
    Button scanButton;
    ImageScanner scanner;
    private boolean barcodeScanned = false;
    private boolean previewing = true;

    Context context;
    boolean alarmCancel;
    private boolean useMyBarcode;
    private String userBarCode;

    //private LinearLayout llParentReader;


    static {
        System.loadLibrary("iconv");
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Признак того что это...запись в настройки штрих кода или ввод ШК для отключения
        alarmCancel = getIntent().getBooleanExtra("AlarmCancel",false);
        context = getApplicationContext();

//        llParentReader = (LinearLayout)findViewById(R.id.ll_parent_reader);
//        Util.getInstance(context).setTheme(llParentReader);

        //Получаем настройки пользователя
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        useMyBarcode = sp.getBoolean("useMyBarCode", false);
        userBarCode = getSharedPreferences("pref", MODE_PRIVATE).getString("myBarCode", "");

        //Toast.makeText(this, "userBarCode = "+userBarCode, Toast.LENGTH_SHORT).show();

        setContentView(R.layout.barcode_reader_activity);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

        scanText = (TextView)findViewById(R.id.scanText);

        scanButton = (Button)findViewById(R.id.ScanButton);

        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (barcodeScanned) {
                    barcodeScanned = false;
                    scanText.setText("Scanning...");
                    mCamera.setPreviewCallback(previewCb);
                    mCamera.startPreview();
                    previewing = true;
                    mCamera.autoFocus(autoFocusCB);
                }
            }
        });
    }

    public void onPause() {
        super.onPause();
        releaseCamera();
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing)
                mCamera.autoFocus(autoFocusCB);
        }
    };

    PreviewCallback previewCb = new PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Parameters parameters = camera.getParameters();
            Size size = parameters.getPreviewSize();

            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {
                previewing = false;
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();

                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {

                    scanText.setText("scanned barcode " + sym.getData());

                    if(!alarmCancel)
                        setBarCodeSettings(sym.getData());
                    else{
                        processingResult(sym.getData());
                    }

                    barcodeScanned = true;
                }
            }
        }
    };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void setBarCodeSettings(String barCod){
        SharedPreferences settings = getSharedPreferences("pref", MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("myBarCode", barCod);
        editor.commit();
        Toast.makeText(this, "barcode "+barCod+" commit", Toast.LENGTH_SHORT).show();
        finish();
    }

    private void processingResult(String barcode){
        if(useMyBarcode && userBarCode.length() != 0){
            if(userBarCode.equals(barcode))
                returnResult();
            else
                Toast.makeText(this, "Wrong barcode", Toast.LENGTH_SHORT).show();
        }
        else
            returnResult();
    }

    private void returnResult(){
        Intent intent = new Intent();
        intent.putExtra("barcodeScanned", true);
        setResult(RESULT_OK, intent);
        finish();
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        Util.getInstance(context).setTheme(llParentReader);
//    }
}